# Contributor: Natanael Copa <ncopa@alpinelinux.org>
# Maintainer: Sertonix <sertonix@posteo.net>
pkgname=apk-tools3
pkgver=3.0.0_pre3_git20241029
_commit=16d93ac94489857db6036e64a1abd7484a4898a5
pkgrel=0
pkgdesc="Alpine Package Keeper v3 - package manager for alpine"
arch="all"
url="https://git.alpinelinux.org/apk-tools"
license="GPL-2.0-only"
subpackages="$pkgname-dbg $pkgname-dev $pkgname-static $pkgname-doc $pkgname-libs"
depends="musl>=1.2.3_git20230424"
depends_doc="!apk-tools-doc"
_lua="5.3"
makedepends_build="meson openssl>3 lua$_lua lua$_lua-lzlib scdoc"
makedepends_host="zlib-dev zstd-dev openssl-dev zlib-static zstd-static openssl-libs-static linux-headers"
if [ "$CBUILD" = "$CHOST" ]; then
	subpackages="$subpackages lua$_lua-apk3:luaapk"
	makedepends_host="$makedepends_host lua$_lua-dev"

	# ca-certificates-bundle needed for https certificate validation
	depends="$depends ca-certificates-bundle"
fi
source="$pkgname-$pkgver.tar.gz::https://gitlab.alpinelinux.org/alpine/apk-tools/-/archive/$_commit/apk-tools-$_commit.tar.gz
	lua-module.patch
	"
builddir=$srcdir/apk-tools-$_commit

build() {
	export VERSION=$pkgver-r$pkgrel

	abuild-meson \
		--auto-features=disabled \
		--bindir=/sbin \
		-Dlua_version=$_lua \
		-Dlua="$([ "$CBUILD" = "$CHOST" ] && echo enabled || echo disabled)" \
		-Ddocs=enabled \
		-Dhelp=enabled \
		output
	ninja -C output

	abuild-meson \
		--auto-features=disabled \
		-Dc_link_args="$CFLAGS -static" \
		-Ddefault_library=static \
		-Dprefer_static=true \
		output-static
	ninja -C output-static src/apk
}

check() {
	meson test --no-rebuild --print-errorlogs -C output
}

package() {
	DESTDIR="$pkgdir" meson install --no-rebuild -C output
	install -d "$pkgdir"/lib/apk/db \
		"$pkgdir"/lib/apk/exec \
		"$pkgdir"/etc/apk/keys \
		"$pkgdir"/etc/apk/protected_paths.d
}

static() {
	pkgdesc="$pkgdesc (static binary)"
	depends=""

	install -Dm755 "$builddir"/output-static/src/apk "$subpkgdir"/sbin/apk.static
	${CROSS_COMPILE}strip "$subpkgdir"/sbin/apk.static
	local pubkey="${PACKAGER_PUBKEY:-$PACKAGER_PRIVKEY.pub}"
	openssl dgst -sha1 -sign "$PACKAGER_PRIVKEY" \
		-out "$subpkgdir"/sbin/apk.static.SIGN.RSA."${pubkey##*/}" \
		"$subpkgdir"/sbin/apk.static
	openssl dgst -sha256 -sign "$PACKAGER_PRIVKEY" \
		-out "$subpkgdir"/sbin/apk.static.SIGN.RSA.sha256."${pubkey##*/}" \
		"$subpkgdir"/sbin/apk.static

}

luaapk() {
	pkgdesc="Lua module for $pkgname"
	depends="!${subpkgname%3}"
	amove usr/lib/lua
}

sha512sums="
815718549f6e9b1ee17fa7d37110fe70b466cd635818efd7447b3a8224597e6d62dcd3e7d5a553f7f9988de7006ef676ce9a3613ac19336d3d5e6a5cb5c8d392  apk-tools3-3.0.0_pre3_git20241029.tar.gz
7a7fdc0225938e6babeca18b4dcb91b2742449aa6d71a94e2739f3018c69ef738877fd3abf79813002cf2d761bf67a67a6d00587b9ba97371aeb3f50957ce447  lua-module.patch
"
